# 天气数据处理
from calculate import calculate
import parsel

from getInfoByRequest import getInfoByRequest
from pandasData import pandasData
from pyCharts import pyCharts


class weatherData:
    # 城市代码
    citytoCode = {
        "北京": "54511",
        "上海": "58367",
        "天津": "54517",
        "重庆": "57516",
        "哈尔滨": "50953",
        "长春": "54161",
        "沈阳": "54342",
        "呼和浩特": "53463",
        "石家庄": "53698",
        "太原": "53772",
        "郑州": "57083",
        "济南": "54823",
        "南京": "58238",
        "杭州": "58457",
        "合肥": "58321",
        "福州": "58847",
        "南昌": "58606",
        "长沙": "57687",
        "广州": "59287",
        "南宁": "59432",
        "海口": "59758",
        "成都": "56294",
        "贵阳": "57816",
        "昆明": "56778",
        "拉萨": "55591",
        "西安": "57036",
        "兰州": "52889",
        "银川": "53614",
        "西宁": "52866",
        "乌鲁木齐": "51463",
    }

    def __init__(self):
        pass

    # 获取并解析天气数据
    def get_weather_data(self, city_name, year):
        month_name = ['', '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月',
                      '十二月']

        weather_data = {}  # 每部字典项是一个月份名和对应月份的每一天的平均气温数据

        # 横坐标
        x_data = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']

        avg_data_per_city = []  # 第一项是城市名，第二项是年份，第三项是该城市所有月份的平均气温数据
        max_data_per_city = []
        min_data_per_city = []

        # 获取每个城市该年度每个月的天气数据
        for city in city_name:
            avg_temperature = [city, year]  # 存平均气温数据 还有城市名字和年份
            max_temperature = [city, year]  # 存最高气温数据
            min_temperature = [city, year]  # 存最低气温数据
            for month in range(1, 13):
                # 构造 url 地址
                city_code = self.citytoCode[city]
                print(f'正在获取 {city} {city_code} {year} 年 {month_name[month]} 的天气数据...')
                url = f'http://tianqi.2345.com/Pc/GetHistory?areaInfo[areaId]={city_code}&areaInfo[areaType]=2&date[year]={year}&date[month]={month}'

                # 获取响应数据
                response = getInfoByRequest.get_weather_data(url, Referer='http://tianqi.2345.com/wea_history/58606.htm')
                if response is None:
                    print('请求失败')
                    avg_temperature.append(None)
                    max_temperature.append(None)
                    min_temperature.append(None)
                    continue
                else:
                    month_max = 0.0
                    month_min = 100.0
                    html_data = response
                    # 解析数据
                    dataSelector = parsel.Selector(html_data)  # 构造解析对象
                    trs = dataSelector.css('table tr')[1:]  # 每一个 tr 是每一天的数据
                    tds = []  # 每一个 td 是一天的数据中的所有属性 tds 存放的就是这个月中的所有属性的列表
                    total_month = 0.0  # 每个月的总气温
                    for tr in trs:  # 这个循环遍历每一天的数据 最后将这个月的数据存到 tds 中
                        # tr 是一行 td 是对 tr 的解构
                        td = tr.css('td::text').getall()
                        # 计算当天的平均气温
                        avg = calculate.getTheAverageTemperatureForTheDay(td)
                        total_month += avg
                        td.append(str(avg))  # 将平均气温插入到列表中 列表中加一个属性
                        tds.append(td)  # 将今天的数据加入到 tds 中

                        # 计算最高气温和最低气温
                        month_max = max(month_max, int(td[1].replace('°', '')))
                        month_min = min(month_min, int(td[2].replace('°', '')))

                    # 计算该月平均气温
                    if len(tds) != 0:
                        month_avg = round(total_month / len(tds), 1)
                    else:
                        month_avg = None

                    weather_data[month_name[month]] = tds
                    avg_temperature.append(month_avg)
                    max_temperature.append(month_max)
                    min_temperature.append(month_min)

            # 计算每个月的平均气温数组
            avg_data_per_city.append(avg_temperature)  # 每个城市的数据存进去
            max_data_per_city.append(max_temperature)
            min_data_per_city.append(min_temperature)

        # 生成折线图
        pyCharts.generateAndLayoutCharts(x_data, avg_data_per_city,max_data_per_city,min_data_per_city)
        # 存入文件
        pandasData.getDataFrameByWeather(avg_data_per_city,'平均')
        pandasData.getDataFrameByWeather(max_data_per_city,'最高')
        pandasData.getDataFrameByWeather(min_data_per_city,'最低')